<template>
  <div class="table-box">
    <div :style="{ height: tableHeight + 'px', position: 'relative' }">
      <div
        class="table-headers"
        v-if="ids.length && pageType != 'receivable' && pageType != 'receivablePlan'"
      >
        <div class="t-l">
          <div class="radios">
            <el-checkbox
              v-model="checkAll"
              @click="changeVal"
              :indeterminate="isIndeterminate"
            ></el-checkbox>
          </div>
          <div class="ids-length">已经选中{{ ids.length }}项</div>
          <div
            class="w-18px h-18px ml-5px mt-2px flex items-center justify-center"
            style="background-color: #ebecf0; border-radius: 4px; cursor: pointer"
          >
            <el-icon size="14" color="#" @click="clearAll"><Close /></el-icon>
          </div>
        </div>
        <div class="t-r">
          <div class="tr-btn mr-8px" @click="transfer">
            <el-icon class="mr-5px"><Sort /></el-icon>
            <span>转移</span>
          </div>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleSelectionChange"
        @select-all="selectAll"
        @select="selectData"
        :header-cell-style="getRowClass"
        @sort-change="sortChangeTable"
        ref="sortTable"
        @row-click="rowClick"
        border
        :data="list"
        height="100%"
        :header-row-style="{ height: '48px', color: '#6b778c' }"
        style="width: 100%; cursor: pointer"
      >
        <el-table-column type="selection" width="55" />
        <template v-for="column in meterHeaderList" :key="column.sort">
          <el-table-column
            :sortable="column.custom"
            :width="column.width"
            v-if="column.show"
            :prop="column.prop"
            :label="column.label"
            :fixed="column.fixed"
          >
            <template #header v-if="column.prop == 'mobiles'">
              <el-button size="small" disabled style="padding: 0 2px">
                <Icon icon="ep:phone" />
              </el-button>
            </template>
            <template #default="scope">
              <div v-if="column.prop == 'mobiles'">
                <el-dropdown
                  v-if="scope.row.mobile && scope.row.telephone"
                  trigger="hover"
                  placement="bottom"
                  size="small"
                  style="position: absolute; right: 0; top: 0"
                >
                  <div class="w-50px h-42px" style="cursor: pointer">
                    <Icon style="margin: 10px 12px" icon="ep:phone" />
                  </div>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        style="padding: 8px 15px"
                        @click="onCall(scope.row, scope.row.mobile)"
                      >
                        <Icon icon="ep:phone" /> 手机号
                      </el-dropdown-item>
                      <el-dropdown-item
                        style="padding: 8px 15px"
                        @click="onCall(scope.row, scope.row.telephone)"
                      >
                        <Icon icon="ep:phone" />
                        电话
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-link :underline="false" v-else-if="scope.row.mobile"
                  ><Icon @click="onCall(scope.row, scope.row.mobile)" icon="ep:phone"
                /></el-link>
                <el-link :underline="false" v-else-if="scope.row.telephone"
                  ><Icon @click="onCall(scope.row, scope.row.telephone)" icon="ep:phone"
                /></el-link>
              </div>
              <div v-if="column.prop == 'name'" class="flex items-center w-200px">
                <el-link type="primary" class="!color-#0052cc">
                  {{ scope.row.name }}
                </el-link>
              </div>
              <div v-if="column.prop == 'customerName'">
                <el-link type="primary" class="!color-#0052cc">
                  {{ scope.row.customerName }}
                </el-link>
              </div>
              <div v-if="column.prop == 'businessName'">
                <el-link type="primary" class="!color-#0052cc">
                  {{ scope.row.businessName }}
                </el-link>
              </div>
              <div v-if="column.prop == 'orderDate'">
                {{ formatDate(scope.row.orderDate).substr(0, 10) }}
              </div>
              <div v-if="column.prop == 'startTime'">
                {{ formatDate(scope.row.startTime).substr(0, 10) }}
              </div>
              <div v-if="column.prop == 'endTime'">
                {{ formatDate(scope.row.endTime).substr(0, 10) }}
              </div>
              <div v-if="column.prop == 'totalReceivablePrice'">
                <span class="color-#ff991f">{{
                  erpPriceInputFormatter(scope.row.totalReceivablePrice)
                }}</span>
              </div>
              <div v-if="column.prop == 'price'">
                <span class="color-#ff991f">{{ erpPriceInputFormatter(scope.row.price) }}</span>
              </div>
              <div v-if="column.prop == 'totalPrice'">
                <span class="color-#ff991f">{{
                  erpPriceInputFormatter(scope.row.totalPrice)
                }}</span>
              </div>
              <div v-if="column.prop == 'returnType'">
                <dict-tag
                  :type="DICT_TYPE.CRM_RECEIVABLE_RETURN_TYPE"
                  :value="scope.row.returnType"
                />
              </div>
              <div v-if="column.prop == 'contract.totalPrice'">
                <span class="color-#ff991f">{{
                  erpPriceInputFormatter(scope.row.contract.totalPrice)
                }}</span>
              </div>
              <div v-if="column.label == '未回款金额（元）'">
                <span class="color-#ff991f">{{
                  erpPriceInputFormatter(scope.row.totalPrice - scope.row.totalReceivablePrice)
                }}</span>
              </div>
              <div v-if="column.prop == 'period'">
                <span class="color-#0052cc">{{ scope.row.period }}</span>
              </div>

              <div v-if="column.label == '实际回款金额（元）'">
                <el-text v-if="scope.row.receivable" class="!color-#ff991f">
                  {{ erpPriceInputFormatter(scope.row.receivable.price) }}
                </el-text>
                <el-text v-else>{{ erpPriceInputFormatter(0) }}</el-text>
              </div>
              <div v-if="column.prop == 'receivable.returnTime'">
                {{ formatDate(scope.row.updateTime).substr(0, 10) }}
              </div>
              <div v-if="column.label == '剩余回款金额（元）'">
                <el-text v-if="scope.row.receivable" class="!color-#ff991f">
                  {{ erpPriceInputFormatter(scope.row.price - scope.row.receivable.price) }}
                </el-text>
                <el-text v-else>{{ erpPriceInputFormatter(scope.row.price) }}</el-text>
              </div>
              <div v-if="column.prop == 'no' && pageType == 'receivable'">
                <span class="color-#0052cc">{{ scope.row.no }}</span>
              </div>
              <div v-if="column.prop == 'contractNo' && pageType == 'receivable'">
                <span class="color-#0052cc">{{ scope.row.contract.no }}</span>
              </div>
              <div v-if="column.prop == 'contractNo'">
                <span class="color-#0052cc"> {{ scope.row.contractNo }}</span>
              </div>
              <div v-if="column.prop == 'source' && scope.row.source">
                <dict-tag :type="DICT_TYPE.CRM_CUSTOMER_SOURCE" :value="scope.row.source" />
              </div>
              <div v-if="column.prop == 'ownerTime'">
                {{ formatDate(scope.row.ownerTime) }}
              </div>
              <div v-if="column.prop == 'industryId'">
                <dict-tag :type="DICT_TYPE.CRM_CUSTOMER_INDUSTRY" :value="scope.row.industryId" />
              </div>
              <div v-if="column.prop == 'dataType'">
                <dict-tag :type="DICT_TYPE.CRM_DATA_TYPE" :value="scope.row.dataType" />
              </div>

              <div v-if="column.prop == 'master'">
                <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.master" />
              </div>
              <div v-if="column.prop == 'parentName'">
                {{ scope.row.parentName }}
              </div>
              <div v-if="column.prop == 'sex'">
                <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex" />
              </div>
              <div v-if="column.prop == 'remindTime'">
                {{ formatDate(scope.row.remindTime).substr(0, 10) }}
              </div>
              <div v-if="column.prop == 'dealTime'">
                {{ formatDate(scope.row.dealTime).substr(0, 10) }}
              </div>
              <div v-if="column.prop == 'returnTime'">
                {{ formatDate(scope.row.returnTime).substr(0, 10) }}
              </div>
              <div v-if="column.prop == 'lastCallTime'">
                {{ formatDate(scope.row.lastCallTime) }}
              </div>
              <div v-if="column.prop == 'lastAcceptTime'">
                {{ formatDate(scope.row.lastAcceptTime) }}
              </div>
              <div v-if="column.prop == 'contactNextTime'">
                {{ formatDate(scope.row.contactNextTime) }}
              </div>
              <div v-if="column.prop == 'contactLastTime'">
                {{ formatDate(scope.row.contactLastTime) }}
              </div>
              <div v-if="column.prop == 'updateTime'">
                {{ formatDate(scope.row.updateTime) }}
              </div>
              <div v-if="column.prop == 'createTime'">
                <span>
                  {{ formatDate(scope.row.createTime) }}
                </span>
              </div>
              <div v-if="column.prop == 'auditStatus'">
                <dict-tag :type="DICT_TYPE.CRM_AUDIT_STATUS" :value="scope.row.auditStatus" />
              </div>
              <div v-if="setTimes[column.prop]">
                <span>
                  {{
                    scope.row[setTimes[column.prop]]
                      ? formatDate(Number(scope.row[setTimes[column.prop]]))
                      : ''
                  }}
                </span>
              </div>
            </template>
          </el-table-column>
        </template>
        <el-table-column align="center" fixed="right" min-width="100" v-if="pageType == 'contract'">
          <template #header>
            <div class="flex items-center justify-around">
              <span>操作</span>
            </div>
          </template>
          <template #default="scope">
            <el-button
              v-if="scope.row.auditStatus === 0"
              v-hasPermi="['crm:contract:update']"
              link
              type="primary"
              class="!color-#0052cc"
              @click="handleSubmit(scope.row)"
            >
              提交审核
            </el-button>
            <el-button
              v-else
              link
              class="!color-#0052cc"
              v-hasPermi="['crm:contract:update']"
              type="primary"
              @click="handleProcessDetail(scope.row)"
            >
              查看审批
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          fixed="right"
          min-width="100"
          v-if="pageType == 'receivable'"
        >
          <template #header>
            <div class="flex items-center justify-around">
              <span>操作</span>
            </div>
          </template>
          <template #default="scope">
            <el-button
              v-if="scope.row.auditStatus === 0"
              v-hasPermi="['crm:receivable:update']"
              link
              type="primary"
              @click="handleSubmits(scope.row)"
            >
              提交审核
            </el-button>
            <el-button
              v-else
              v-hasPermi="['crm:receivable:update']"
              link
              type="primary"
              @click="handleProcessDetails(scope.row)"
            >
              查看审批
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dropdown
        trigger="hover"
        placement="bottom"
        size="small"
        style="position: absolute; right: 0; top: 0"
      >
        <div class="header-sort">
          <el-icon><Operation /></el-icon>
        </div>
        <template #dropdown>
          <TableHeadSort style="right: 100px" :listData="meterHeaderList">
            <div class="mr-20px mt-0 flex justify-end">
              <el-button @click="handleDefaultValue" size="small">恢复默认</el-button>
              <el-button @click="saveTableSortValue" type="primary" size="small"
                >保存配置</el-button
              >
            </div>
          </TableHeadSort>
        </template>
      </el-dropdown>
    </div>
    <div class="page-box">
      <Pagination
        style="margin: 0 !important"
        :total="total"
        :page="pageNo"
        :limit="pageSize"
        @pagination="pageGet"
      />
    </div>
  </div>
  <!-- 转移弹窗 -->
  <CrmTransferForm ref="transferFormRef" @success="getPage" />
  <!-- 详情弹窗 -->
  <CrmSpec ref="crmSpec" @getPage="getPage" />
</template>
<script setup>
import { erpPriceInputFormatter, erpPriceTableColumnFormatter } from '@/utils'
import CrmTransferForm from '@/views/crm/permission/components/TransferForm.vue'
import { TableHeadSort } from '@/components/TableHeadSort/index'
import { BizTypeEnum } from '@/api/crm/permission'
import FollowUpRecordForm from '@/views/crm/followup/FollowUpRecordForm.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import {
  Operation,
  Close,
  MoreFilled,
  UserFilled,
  Sort,
  CirclePlusFilled,
  EditPen,
  Delete,
  Phone
} from '@element-plus/icons-vue'
import WebPhone from '@/hooks/web/useCall'
import * as ContactApi from '@/api/crm/contact'
import * as BusinessApi from '@/api/crm/business'
import * as ContractApi from '@/api/crm/contract'
import * as ReceivableApi from '@/api/crm/receivable'

const message = useMessage()
const { t } = useI18n()
const emit = defineEmits([
  'pageNextProver',
  'ordinaryOrAdvancedRequest',
  'handleDefault',
  'saveTableSort',
  'sortChange'
])
const props = defineProps({
  pageType: String,
  list: [],
  loading: Boolean,
  meterHeaderList: Array,
  total: Number,
  pageNo: Number,
  pageSize: Number,
  domHeight: Number,
  setTimes: Object
})
const tableHeight = ref(0)
const isIndeterminate = ref(false)
const checkAll = ref(false)
// 设置表格的
const setTableHeight = (val) => {
  tableHeight.value = val
}
defineExpose({ setTableHeight })
watch(
  () => props.domHeight,
  (value) => {
    tableHeight.value = value
  },
  { deep: true, immediate: true }
)
const closeTag = ref()
/**多选合集*/
const ids = ref([])
// 全部选择了
const selectAll = (val) => {
  checkAll.value = val.length == 0 ? false : true
}
const sortTable = ref(null)
const changeVal = (val) => {
  sortTable.value.toggleAllSelection()
}
/**清除所有选中项*/
const clearAll = () => {
  sortTable.value.clearSelection()
}
/**选择数据*/
const selectData = (val) => {
  if (val.length == props.list.length) {
    checkAll.value = true
    isIndeterminate.value = false
  } else {
    if (val.length) {
      isIndeterminate.value = true
    } else {
      isIndeterminate.value = false
    }
  }
}
/** 合同提交审核 **/
const handleSubmit = async (row) => {
  await message.confirm(`您确定提交【${row.name}】审核吗？`)
  await ContractApi.submitContract(row.id)
  message.success('提交审核成功！')
  emit('ordinaryOrAdvancedRequest')
}
/**回款提交审核*/
const handleSubmits = async (row) => {
  await message.confirm(`您确定提交编号为【${row.no}】的回款审核吗？`)
  await ReceivableApi.submitReceivable(row.id)
  message.success('提交审核成功！')
  emit('ordinaryOrAdvancedRequest')
}
/** 合同查看审批 */
const handleProcessDetail = (row) => {
  push({ name: 'BpmProcessInstanceDetail', query: { id: row.processInstanceId } })
}
/*回款查看审批*/
const handleProcessDetails = (row) => {
  push({ name: 'BpmProcessInstanceDetail', query: { id: row.processInstanceId } })
}
/**call*/
const onCall = (row, callee) => {
  WebPhone.getInstance().call({
    callee,
    source: 'clue',
    sourceId: row.id
  })
}
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  ids.value = val.map((item) => {
    return item.id
  })
}
/** 处理样式 */
const getRowClass = ({ row, column, rowIndex, columnIndex }) => {
  if (column.property == closeTag.value) {
    column.order = ''
  }
}
/** 标签排序 */
const sortChangeTable = (column) => {
  if (column.prop == 'levelRespVO') {
    emit(
      'sortChange',
      'levelValue',
      column.order ? (column.order == 'descending' ? 'desc' : 'asc') : ''
    )
  } else {
    emit(
      'sortChange',
      column.prop,
      column.order ? (column.order == 'descending' ? 'desc' : 'asc') : ''
    )
  }
}
/*列表的数据刷新*/
const getPage = () => {
  emit('ordinaryOrAdvancedRequest')
}
const { push } = useRouter()

/**分页*/
const pageGet = (val) => {
  emit('pageNextProver', val)
}

/** 恢复默认 */
const handleDefaultValue = () => {
  emit('handleDefault')
  message.success('保存成功')
}
const saveTableSortValue = () => {
  emit('saveTableSort')
  message.success('保存成功')
}
// 转移
const transferFormRef = ref()
const transfer = () => {
  if (props.pageType == 'contact') {
    transferFormRef.value?.open(true, '联系人转移', ids.value, ContactApi.batchTransferContact)
  } else if (props.pageType == 'business') {
    transferFormRef.value?.open(true, '商机转移', ids.value, BusinessApi.batchTransferBusiness)
  } else if (props.pageType == 'contract') {
    transferFormRef.value?.open(true, '合同转移', ids.value, ContractApi.batchTransferContract)
  }
}
const crmSpec = ref(null)
/**选中一行*/
const rowClick = (row, column) => {
  if (column.property == undefined) return
  if (column.property == 'customerName') {
    const nowIds = props.list.filter((item) => item.customerId).map((item) => item.customerId)
    crmSpec.value.setDrawer(true, 'customer', row.customerId, nowIds)
  } else if (column.property == 'businessName') {
    const nowIds = props.list.filter((item) => item.businessId).map((item) => item.businessId)
    crmSpec.value.setDrawer(true, 'business', row.businessId, nowIds)
  } else if (column.property == 'contractNo') {
    const nowIds = props.list.filter((item) => item.contractId).map((item) => item.contractId)
    crmSpec.value.setDrawer(true, 'contract', row.contractId, nowIds)
  } else if (column.property != 'mobile' && column.property != 'followUpStage') {
    const nowIds = props.list.map((item) => item.id)
    crmSpec.value.setDrawer(true, props.pageType, row.id, nowIds)
  }
}
</script>
<style scoped lang="scss">
.table-box {
  background-color: #fff;
  box-shadow: 0 2px 8px #172b4d1a;
  position: relative;
  padding-bottom: 64px;
  .page-box {
    width: calc(100% - 32px);
    padding: 16px;
    position: absolute;
    bottom: 0;
    left: 0;
    height: 32px;
    text-align: right;
  }
}
.header-sort {
  width: 34px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  background-color: #ebecf0;
  position: absolute;
  right: 2px;
  top: 2px;
  z-index: 9;
  cursor: pointer;
}
.table-headers {
  width: 100%;
  height: 48px;
  background-color: #42526e;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9;
  display: flex;
  align-items: center;
  .t-l {
    width: 180px;
    display: flex;
    align-items: center;
    .radios {
      width: 43px;
      text-align: center;
      line-height: 48px;
      padding: 0 12px 0 0;
    }
    .ids-length {
      color: #fff;
      font-size: 14px;
    }
  }
  .t-r {
    width: calc(100% - 180px);
    height: 100%;
    overflow-x: auto;
    display: flex;
    align-items: center;
    .tr-btn {
      font-size: 14px;
      color: #fff;
      display: flex;
      align-items: center;
      padding: 8px 15px;
      cursor: pointer;
      flex-shrink: 0;
    }
    .tr-btn:hover {
      background: #fff;
      color: #626976;
      border-radius: 4px;
      flex-shrink: 0;
    }
  }
  .t-r::-webkit-scrollbar {
    height: 8px;
  }

  .t-r::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }

  .t-r::-webkit-scrollbar-thumb {
    background: #c1c7d0;
    border-radius: 4px;
  }

  .t-r::-webkit-scrollbar-thumb:hover {
    background: #c1c7d0;
  }
}
.label-list {
  display: flex;
  align-items: center;
}
</style>
